// pages/textPay/index.js
const app = getApp();
import getUserCard from "../../utils/getUserCard.js";
const util = require('../../utils/util.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    createUid: 0,
    cardId: 0,
    employeeid: 0,
    cardInfo: '',
    payMoney: 0, //实际支付金额
    isInput: false,
    inputNumber: '', //消费金额
    cutmoney: false,
    isInputCut: false,
    inputNumberCut: '', //不参与优惠金额
    cutType: 0, //优惠方式：1优惠券，2会员折扣，3充值卡
    coupon_isopen: 0,
    card_isopen: 0,
    carditem_isopen: 0,
    vipcardinfo: {},
    cardItemlist: [],
    showCarditemList: false,
    showCouponList: false,
    couponList: [], //用户所有可使用的优惠券
    discountMoney: 0, //支付时使用的会员卡优惠金额
    cardItemMoney: 0, //选择使用的充值卡余额
    carditemid: 0, //选择使用的充值卡id
    discount: 0, //充值卡支付比例
    couponid: 0,//选择的优惠券
    couponmoney: 0,//优惠券可减金额
    is_append: false,
    cardItemType: 1,//1充值卡4玖玖卡5锦鲤卡
    universalCard: 2,//0没买过玖玖通用卡，1已买通用卡
    seleGif: true,//是否选择赠送玖玖卡
    rateCoupon: {money: 0, couponSN: ''} //费率补贴优惠券
  },

  changeUseCard: function () {
    this.setData({
      seleGif: !this.data.seleGif
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log("onload当面付", options);    
    let that = this;
    if (options.q) {
      let url = decodeURIComponent(options.q);  
      this.setData({
        createUid: util.getQuery(url,'createUid'),
        employeeid: util.getQuery(url,'employeeid'),
        cardId: util.getQuery(url,'id')
      })
    }
    if (options.createUid) {
      if (options.employeeid) {
        employeeid = options.employeeid;
      }
      this.setData({
        createUid: options.createUid,
        cardId: options.id
      })
    }
    that.getAiCardInfo(that.data.cardId);
    that.getAdvert();//广告
  },
  paymentOrder: function () {
    let that = this;
    let couponid = 0;
    let carditemid = 0;
    let discountMoney = 0;  
    let notIn = that.data.inputNumberCut;
    let cutType = that.data.cutType;
    let cutmoney = that.data.cutmoney;    
    if (cutType == 1) {
      couponid = that.data.couponid;
    }
    if (cutType == 2) {
      discountMoney = that.data.discountMoney;
    }
    if (cutType == 3) {
      carditemid = that.data.carditemid;
    }
    if (notIn == '' || !cutmoney) {
      notIn = 0;
    }
    let orderAmount = that.data.inputNumber; //付款金额
    let notInMoney = parseFloat(notIn); //不参与优惠金额
    if (orderAmount=='' || isNaN(orderAmount)) {
      util.showToast('请输入金额'); 
      return;
    }
    if (orderAmount.toString().length > 10) {
      util.showToast('输入金额过大'); 
      return;
    }
    if (notInMoney > parseFloat(orderAmount)) {
      util.showToast('不参与优惠金额不能大于消费金额');  
      return;
    }

    wx.showLoading({title: '去支付...',mask: true,})
    wx.request({
      url: app.globalData.host + '/api/order/SubmitDirectPaymentOrder',
      data: {
        uid: app.globalData.userInfo.Uid,
        Cashier: that.data.createUid,
        storeid: app.globalData.storeId,
        OrderAmount: orderAmount,
        employeeid: that.data.employeeid,
        DiscountMoney: discountMoney,
        CardItemId: carditemid,
        NotInMoney: notInMoney,
        Promotion: cutType,
        IsReceiveCard: that.data.seleGif ? 1: 0,
        CouponIdList: couponid,       
        rateCouponSN: that.data.rateCoupon.couponSN,
        PayType: 'wechat'
      },
      success: function (res) {
        wx.hideLoading();
        if (res.data.Code == 0) {
          let oid = res.data.Data;
          let isReceiveCard = that.data.seleGif ? 1: 0;
          that.toPay(oid, isReceiveCard);
        } else {
          util.showModal(res.data.Message);
        }
      }
    })
  },
  // 付款
  toPay: function (oid, isReceiveCard) {
    let that = this;
    wx.request({
      url: app.globalData.host + '/api/WeChat/OpenPay',
      data: {
        uid: app.globalData.userInfo.Uid,
        createUid: that.data.createUid,
        oid: oid
      },
      method: 'POST',
      success: function (res) {
        if (res.data.Code == 0) {
          if (res.data.Data.trade_state == "SUCCESS") {
            util.showToast('支付成功','success');            
            if (that.data.universalCard == 1) {//已经买过玖玖卡,跳平台首页(改为传单礼包)
              that.getSaleInfo();
            } else if (isReceiveCard == 0) {//跳到玖玖卡详情页购买
              that.getSaleInfo();
            }
          } else {
            if (res.data.Data.prepayId != app.globalData.prepayId) {
              // 发起支付
              wx.requestPayment({
                timeStamp: res.data.Data.timeStamp,
                nonceStr: res.data.Data.nonceStr,
                package: 'prepay_id=' + res.data.Data.prepayId,
                signType: 'MD5',
                paySign: res.data.Data.paySign,                
                success: function (ress) {
                  that.receiveCoupon(1);
                  if (that.data.universalCard == 1) {//已经买过玖玖卡
                    that.getSaleInfo();
                  } else {
                    that.getSaleInfo(isReceiveCard);
                  }
                }
              })
              app.globalData.prepayId = res.data.Data.prepayId;
            }
          }
        } else {
          util.showModal(res.data.Message);
          return;
        }
      }
    })
  },
  // 获取传单礼包统计数据
  getSaleInfo: function (isReceive = 0) {
    let that = this;
    wx.request({
      url: app.globalData.host + '/api/leaflet/GetPackageTotal?uid=' + app.globalData.userInfo.Uid + '&shareUid=' + that.data.createUid,
      success: function (res) {
        if (res.data.Code == 0) {
          if (res.data.Data.StaffCount > 0) {//领取传单礼包
            wx.redirectTo({
              url: '/merchant/flyer/receiveLeafletCoupon/index?createUid=' + that.data.createUid + '&showWxcard=' + isReceive,
            })
          } else {
            wx.request({//跳转领取联盟券页面
              url: app.globalData.host + '/api/Alliance/GetAllianceListByApply?uid=' + that.data.createUid,
              success: function (res2) {
                if (res2.data.Code == 0) {
                  let addedList = res2.data.Data.AllianceList;
                  if (addedList.length > 0) {
                    that.getAllianRecord(addedList[0].Id);
                  } else {
                    wx.reLaunch({
                      url: '/pages/indexDefault/index',
                    })
                  }
                } else {
                  wx.reLaunch({
                    url: '/pages/indexDefault/index',
                  })
                }
              }
            })
          }
        }
      }
    })
  },
  
  //复制广告链接并计数
  getAdvert: function () {
    let that = this;
    wx.request({
      url: app.globalData.host + '/api/Advert/VideoAdvert?showUid=' + that.data.createUid + '&isCount=1',
      success: function (res) {
        if (res.data.Code == 0) {
          if (res.data.Data && res.data.Data.Url) {
            wx.setClipboardData({
              data: res.data.Data.Url,
              success(res) {
                util.showToast('请输入金额');
              }
            })
          }
        }
      }
    })
  },

  getAllianRecord: function (allianceId) {
    let cardid = wx.getStorageSync("cardId");
    wx.request({
      url: app.globalData.host + '/api/alliance/GetPackageRecord?allianceid=' + allianceId + '&uid=' + app.globalData.userInfo.Uid,
      success: function (res) {
        if (res.data.Code == 0) {
          if (!res.data.Data) {//没领取过
            wx.redirectTo({
              url: '/merchant/alliance/receiveAllianceCoupon/index?allianceid=' + allianceId + '&id=' + cardid
            })
          } else {
            wx.reLaunch({
              url: '/pages/indexDefault/index',
            })
          }
        } else {
          wx.reLaunch({
            url: '/pages/indexDefault/index',
          })
        }
      }
    })
  },

  clickNumber: function (e) {
    let that = this;
    let clickNumber = e.currentTarget.dataset.number;
    let inputNumber = that.data.inputNumber; //消费金额
    let inputNumberCut = that.data.inputNumberCut; //不参与优惠金额
    if (!that.data.isInputCut) { //消费金额
      that.isInput();
      let sumInput = inputNumber + clickNumber;
      that.setData({
        inputNumber: sumInput
      })
    } else {
      let sumInput = inputNumberCut + clickNumber;
      that.setData({
        inputNumberCut: sumInput
      })
    }
    // 输入消费金额之后才开始计算实付金额
    if (that.data.inputMoney != '') {
      let cardItemlist = that.data.cardItemlist;
      if (cardItemlist.length > 0 && that.data.carditem_isopen == 1) {
        that.setData({
          cutType: 3
        })
      }
      that.caculater(that.data.cutType);
    }
  },

  deleteNumber: function () {
    let that = this;
    if (!that.data.isInputCut) { //消费金额
      let inputNumber = that.data.inputNumber;
      let newNumber = inputNumber.substr(0, inputNumber.length - 1);
      if (newNumber == '') {
        that.setData({
          payMoney: 0
        })
      }
      that.setData({
        inputNumber: newNumber
      })
    } else {
      let inputNumberCut = that.data.inputNumberCut;
      let newNumber = inputNumberCut.substr(0, inputNumberCut.length - 1);
      that.setData({
        inputNumberCut: newNumber
      })
    }
    that.caculater(that.data.cutType);
  },  
  getAiCardInfo: function (cardId) {
    var that = this;    
    wx.request({
      url: app.globalData.host + '/api/Staff/GetInfo?id=' + cardId,
      success: function (res) {
        if (res.data.Code == 0) {
          let cardInfo = res.data.Data;
          var avaters = cardInfo.Slides;
          avaters = avaters.split(',');
          if (avaters.length > 0 && avaters[0]) {
            cardInfo.slide = util.formatAvater(avaters[0], 'https://static.711688.net.cn/upload/card/source/');
          } else {
            cardInfo.slide = util.formatAvater(cardInfo.Avater, 'https://static.711688.net.cn/upload/card/source/');
          }
          that.setData({
            cardInfo: cardInfo
          })
        } else {
          util.showToast('信息获取失败')
          wx.redirectTo({
            url: '/pages/weijieke/cardList/index',
          })
        }
      }
    })
  },
  chooseCouponNew: function (e) {
    let that = this;
    let couponid = e.currentTarget.dataset.couponid;
    let ordermoney = e.currentTarget.dataset.ordermoney;
    let couponmoney = e.currentTarget.dataset.money;
    let inputNumber = that.data.inputNumber; //消费金额
    let notInCutMoney = that.data.inputNumberCut; //不参与优惠金额
    if (inputNumber == '') {
      inputNumber = 0;
    }
    if (notInCutMoney == '') {
      notInCutMoney = 0;
    }
    let inCutMoney = parseFloat(inputNumber) - parseFloat(notInCutMoney);//参与优惠的金额
    if(inCutMoney <= 0){
      util.showToast('请输入消费金额');   
      that.setData({
        cutType: 0
      })
      return;
    }
    if (inCutMoney < ordermoney) {
      util.showToast('不满足满减条件');  
      that.setData({
        cutType: 0
      })
      return;
    } else {
      that.data.couponmoney = couponmoney;
      that.setData({
        couponid: couponid
      })
    }
  },
  updateCouponId: function () {
    if(!this.data.couponid){
      util.showToast('请选择优惠券');  
      return;
    }
    this.setData({
      cutType: 1,
      showCouponList: false,
    })
    this.caculater(1);
  },
  closeCoupon: function () {
    this.setData({
      showCouponList: false,
      showCarditemList: false
    })
  },
  chooseCarditem: function (e) {
    let id = e.currentTarget.dataset.id;
    this.setData({
      carditemid: id
    })
  },
  //选择充值卡支付
  selectCarditem: function (e) { 
    let cardItemlist = this.data.cardItemlist;
    let carditemid = this.data.carditemid;
    let showCarditemList = false;

    if(carditemid > 0){
      carditemid = 0; //选中后,取消选中
    }else if(cardItemlist.length == 1){
      carditemid = cardItemlist[0].Cid;
    } else if(cardItemlist.length > 1){
      showCarditemList =true;
    }
    let cutType = carditemid > 0 ? 3 : 0;
    this.setData({      
      showCarditemList: showCarditemList,
      carditemid: carditemid,
      cutType:  cutType,
      couponid: 0,
      discountMoney: 0,
    })
    this.caculater(cutType);
  },
  //选中优惠券
  selectCoupon: function (e) {
    let type = e.currentTarget.dataset.type;
    let cutType = this.data.cutType;
    let couponid = this.data.couponid;
    let showCouponList = true;
    if (type == cutType) {
      cutType = 0;
      couponid = 0;
      showCouponList = false;
      this.caculater(cutType);
    }
    this.setData({
      cutType: cutType,
      showCouponList: showCouponList,
      couponid: couponid,
    })    
  },
  //选中折扣卡
  selectCard: function (e) {
    let type = e.currentTarget.dataset.type;
    if (type == this.data.cutType) {
      type = 0;
    }
    this.setData({
      cutType: type,
      carditemid: 0,
      couponid: 0
    })
    this.caculater(type);
  },
  //商家的优惠方式
  getDirectPromition: function (cardId,createuid) {
    let that = this;
    wx.request({
      url: app.globalData.host + '/api/coupon/GetDirectPromotion?uid=' + app.globalData.userInfo.Uid + '&createUid=' + createuid + '&staffId=' + cardId + '&paytype=wechat',
      success: function (res) {
        let data = res.data.Data;
        if (res.data.Code == 0) {
          //折扣卡
          let discountCard = '';
          if (data.card) {
            discountCard = data.card;
            discountCard.Discount = (discountCard.Discount * 0.1).toFixed(1);
          }
          //优惠券
          let couponList = data.coupon ? data.coupon : [];     
          //卡项目
          let cardItem = {Cid:0, Balance:0, Discount:0, CardType: 0};
          if (data.carditem.length > 0) {
            for (let i = 0; i < data.carditem.length; i++) {
              let item = data.carditem[i];
              item.ExpireTime = item.ExpireTime.substr(0, 10);
              if (res.data.Data.isBuy && item.CardType == 4) {
                cardItem = item;  //已经有玖玖卡
                //break;
              } else {
                if (item.Balance > cardItem.Balance && item.CardType == 1) {
                  cardItem = item;
                }
              }                      
            }    
          } 
          if (res.data.Data.isBuy) {//是否购买过玖玖卡
            that.setData({
              universalCard: 1,
              seleGif: false
            })
          } else {
            that.setData({
              universalCard: 0
            })
          }
          console.log(data.carditem)
          that.setData({
            vipcardinfo: discountCard,
            couponList: couponList,  
            cardItemlist: data.carditem,
            cardItemMoney: cardItem.Balance,
            carditemid: cardItem.Cid,
            cardItemType: cardItem.cardType,
            discount: cardItem.Discount,
            coupon_isopen: data.coupon ? 1:0,
            card_isopen: data.card ? 1 : 0,
            carditem_isopen: cardItem.Cid >0 ? 1 : 0
          })
        } else {
          util.showModal(res.data.Message);         
        }
      }
    })
  },
  // 计算应付金额
  caculater: function (cutType) {
    let that = this;
    let payMoney = 0;
    let cutmoney = that.data.cutmoney; //是否输入不参与优惠金额
    let notIncutMoney = that.data.inputNumberCut;
    let inputNumber = that.data.inputNumber;
    let discountMoney = that.data.discountMoney;
    let cardItemType = that.data.cardItemType;
    if (inputNumber == '' || inputNumber == '.') {
      inputNumber = 0;
    }
    if (notIncutMoney == '' || !cutmoney) {
      notIncutMoney = 0;
    }
    if(cutType <= 0){ //没有使用优惠
      payMoney = parseFloat(inputNumber).toFixed(2);
      that.setData({payMoney: payMoney})
      return;
    }
    //参与优惠金额
    let inCutMoney = parseFloat(inputNumber) - parseFloat(notIncutMoney); 
    if (inCutMoney <= 0) {
      payMoney = parseFloat(inputNumber);
      that.setData({
        payMoney: payMoney,
        discountMoney: discountMoney
      })
      return;
    }

    if (cutType == 1) { //优惠券 
      payMoney = inCutMoney - parseFloat(that.data.couponmoney) + parseFloat(notIncutMoney);
      payMoney = parseFloat(payMoney).toFixed(2);
      that.setData({
        payMoney: payMoney
      })
    } 

    if (cutType == 2) { //折扣卡
      payMoney = parseFloat(inCutMoney * that.data.vipcardinfo.Discount * 0.1) + parseFloat(notIncutMoney);
      discountMoney = parseFloat(inCutMoney * (1 - that.data.vipcardinfo.Discount * 0.1)).toFixed(2);
    }

    if (cutType == 3) { 
      let cardItemMoney = that.data.cardItemMoney;
      let discount = that.data.discount;
      let cutMoney = parseFloat(inCutMoney * discount * 0.01); //使用充值卡抵扣金额
      if (cardItemType == 5) {//福鲤卡
        payMoney = 0;
        if (cutMoney > cardItemMoney) {
          cutMoney = cardItemMoney;
          payMoney = parseFloat(cutMoney) - parseFloat(cardItemMoney);
        }
      } else {    //玖玖卡
        if (cutMoney > cardItemMoney) {
          cutMoney = cardItemMoney;
        }
        payMoney = parseFloat(inputNumber) - parseFloat(cutMoney);
      }
    }
    payMoney = parseFloat(payMoney).toFixed(2);
    that.setData({
      payMoney: payMoney,
      discountMoney: discountMoney
    })
  },
  
  // 取出所有可使用的优惠券（第一次）
  getCanUseCoupons: function (inCutMoney, notIncutMoney, couponList) {
    let that = this;
    let allcanUselist = [];
    let payMoney = 0;
    for (let i = 0; i < couponList.length; i++) {
      if (inCutMoney >= couponList[i].orderamountlower) {
        allcanUselist.push(couponList[i]);
      }
    }
    if (allcanUselist.length > 0) { //选择第一张可使用的优惠券
      that.chooseCoupons(inCutMoney, notIncutMoney, allcanUselist);
    } else {
      payMoney = parseFloat(inCutMoney) + parseFloat(notIncutMoney);
      that.setData({
        payMoney: parseFloat(payMoney).toFixed(2)
      })
    }
  },
  // 选择优惠券第一张
  chooseCoupons: function (inCutMoney, notIncutMoney, allcanUselist) {
    let that = this;
    let payMoney = 0;
    let temp = 0;
    let index = 0;
    let paymoneyTemp = inCutMoney;
    let is_append = that.data.is_append;
    for (let i = 0; i < allcanUselist.length; i++) {
      if (temp < allcanUselist[i].money) {
        temp = allcanUselist[i].money;
        index = i;
        is_append = allcanUselist[i].is_append;
      }
    }
    paymoneyTemp = parseFloat(paymoneyTemp) - parseFloat(temp);
    allcanUselist.splice(index, 1);
    if (allcanUselist.length > 0) { //选择第二张可使用的优惠券
      that.getCanUseCoupons2(paymoneyTemp, notIncutMoney, allcanUselist, is_append);
    } else {
      payMoney = paymoneyTemp + parseFloat(notIncutMoney);
      that.setData({
        payMoney: payMoney
      })
    }
  },
  //选择第二张优惠券
  getCanUseCoupons2: function (inCutMoney, notIncutMoney, couponList, is_append) {
    let that = this;
    let allcanUselist = [];
    let payMoney = 0;
    for (let i = 0; i < couponList.length; i++) {
      if (is_append) {
        if (inCutMoney >= couponList[i].orderamountlower) {
          allcanUselist.push(couponList[i]);
        }
      } else {
        if (inCutMoney >= couponList[i].orderamountlower && couponList[i].is_append) {
          allcanUselist.push(couponList[i]);
        }
      }
    }
    if (allcanUselist.length > 0) {
      that.chooseCoupons2(inCutMoney, notIncutMoney, allcanUselist);
    } else {
      payMoney = parseFloat(inCutMoney) + parseFloat(notIncutMoney);
      payMoney = parseFloat(payMoney).toFixed(2)
      that.setData({
        payMoney: payMoney
      })
    }
  },
  chooseCoupons2: function (inCutMoney, notIncutMoney, allcanUselist) {
    let that = this;
    let temp = 0;
    let paymoneyTemp = inCutMoney;
    for (let i = 0; i < allcanUselist.length; i++) {
      if (temp < allcanUselist[i].money) {
        temp = allcanUselist[i].money;
      }
    }
    paymoneyTemp = parseFloat(paymoneyTemp) - parseFloat(temp) + parseFloat(notIncutMoney);
    that.setData({
      payMoney: parseFloat(paymoneyTemp).toFixed(2)
    })
  },
  // 选择充值卡
  updateCardItemid: function () {
    let that = this;
    let cardItemMoney = that.data.cardItemMoney;
    let carditemid = that.data.carditemid;
    let carditemList = that.data.cardItemlist;
    let inputNumber = that.data.inputNumber == '' ? 0 : that.data.inputNumber; //消费金额
    let notInCutMoney = that.data.inputNumberCut =='' ? 0 : that.data.inputNumberCut; //不参与优惠金额
    let inCutMoney = parseFloat(inputNumber) - parseFloat(notInCutMoney);
    let discount = 0;
    let payMoney = 0;
    if (inCutMoney <= 0 || inputNumber == 0) {
      payMoney = parseFloat(inputNumber).toFixed(2);
      util.showToast('请输入消费金额');
      that.setData({
        cutType: 0
      })
    } else {
      let cutMoney = 0;
      for (let i = 0; i < carditemList.length; i++) {
        if (carditemList[i].Cid == carditemid) {
          cardItemMoney = carditemList[i].Balance;
          discount = carditemList[i].Discount;
          cutMoney = parseFloat(inCutMoney * discount).toFixed(2); //使用充值卡抵扣金额
          if (carditemList[i].CardType == 5) {//福鲤卡
            payMoney = 0;
            if (cutMoney > cardItemMoney) {
              payMoney = parseFloat(cutMoney) - parseFloat(cardItemMoney);
            }
          } else {
            if (cutMoney > cardItemMoney) {
              cutMoney = cardItemMoney;
            }
            payMoney = parseFloat(inputNumber) - parseFloat(cutMoney);
          }
        }
      }
    }
    that.setData({
      showCarditemList: false,
      cardItemMoney: cardItemMoney,
      discount: discount,
      cutType: 3
    })
    that.caculater(that.data.cutType);
  },

  isInput: function () { //输入消费金额
    this.setData({
      isInput: true,
      isInputCut: false
    })
  },
  isInputCut: function () { //输入不参与优惠金额
    this.setData({
      isInput: false,
      isInputCut: true
    })
  },

  // 是否输入不参与优惠金额
  selIscount: function () {
    this.setData({
      cutmoney: !this.data.cutmoney
    })
    if (this.data.cutmoney) {
      this.setData({
        isInput: false,
        isInputCut: true
      })
    }
    this.caculater(this.data.cutType);
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let that = this;
    if (app.globalData.userInfo && that.data.createUid > 0) {
      that.receiveCoupon();
    } else {
      setTimeout(function () {
        this.onShow();
      }.bind(that), 1000)
    }
  },
  //领券
  receiveCoupon: function (isReceive = 0) {
    let that = this;
    wx.request({
      url: app.globalData.host + '/api/coupon/AutoReceiveCoupon',
      data:{
        uid: app.globalData.userInfo.Uid,
        createUid: that.data.createUid,
        isReceive: isReceive,
        payType: 'wechat'
      },
      success: function (res) {
        if(res.data.Code == 0){
          let coupon = res.data.Data;
          console.log('领费率优惠券',isReceive);
          console.log(coupon);
          that.setData({
            rateCoupon:{money: coupon.Money, couponSN: coupon.CouponSN}
          })
        }else{
          console.log(res.data.Message);
        }
        //有费率优惠券时，不使用其他优惠
        if(that.data.rateCoupon.money <= 0){
          that.getDirectPromition(that.data.cardId, that.data.createUid);
        }
      }
    })
  }
})